package com.gitee.feizns.itrip.personal.utils.component.resolver.argument;

import com.gitee.feizns.itrip.personal.utils.component.annotations.CurtUser;
import com.gitee.feizns.itrip.personal.utils.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 为方法注入缓存在redis中的当前用户
 * @author feizns
 * @since 2019/1/11 0011
 */
public class CurrentUserResolver implements HandlerMethodArgumentResolver {

    /**
     * 参数名称
     */
    private Class<?> curtUserClass;

    @Autowired
    private TokenService tokenService;

    public CurrentUserResolver(Class<?> curtUserClass) {
        this.curtUserClass = curtUserClass;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurtUser.class) && parameter.getParameterType() == curtUserClass;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader(TokenService.TOKEN_HEADER_KEY);
        return token != null ? tokenService.getUser(token) : null;
    }

}
